﻿using Framework.Procedure;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

namespace Framework.UILogic
{

    public class DownloadUI : UIFormLogic
    {
        public Text Content;
        public Button ConfirmButton;
        public Button CancleButton;
        public Image ProgressImage;

        private ProcedureDownloadResource m_procedureDownloadResource;

        
        public override void OnOpen(object userData)
        {
            base.OnOpen(userData);
            gameObject.SetActive(true);
            // base.OnOpen(userData);
            m_procedureDownloadResource = userData as ProcedureDownloadResource;
            Content.text = "更新";
            ConfirmButton.gameObject.SetActive(true);
            CancleButton.gameObject.SetActive(true);
            ProgressImage.gameObject.SetActive(false);
            ProgressImage.fillAmount = 0;
            ConfirmButton.onClick.RemoveAllListeners();
            CancleButton.onClick.RemoveAllListeners();
            
            ConfirmButton.onClick.AddListener(OnConfirm);
            CancleButton.onClick.AddListener(OnCancle);
        }

        // public void Close()
        // {
        //     gameObject.SetActive(false);
        // }
        void OnConfirm()
        {
            m_procedureDownloadResource.Download(this);
            ConfirmButton.gameObject.SetActive(false);
            CancleButton.gameObject.SetActive(false);
            ProgressImage.gameObject.SetActive(true);
            // ConfirmButton.onClick.RemoveAllListeners();
        }

        void OnCancle()
        {
            UnityGameEntry.Shutdown();
        }
        

        public void OnDownloadProgress(int totalDownloadCount, int currentDownloadCount, long totalDownloadBytes,
            long currentDownloadBytes)
        {
            Content.text = $"{totalDownloadCount}/{currentDownloadCount}\n{totalDownloadBytes}/{currentDownloadBytes}";
            ProgressImage.fillAmount = currentDownloadBytes / totalDownloadBytes;
        }

        public void OnDownloadError(string fileName, string error)
        {
            Content.text = $"{fileName}下载错误，{error}";
        }

        public void OnStartDownloadFile(string fileName, long sizeBytes)
        {
            Content.text = $"{fileName}开始下载，大小为{sizeBytes}";
        }
    }

}